package com.ai.dmc.utils.export.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;

import com.ai.dmc.utils.export.ExportSvc;
import com.ai.dmc.utils.zip.ZipUtil;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

/**
 */
public class PdfExportSvcImpl implements ExportSvc {

	private String filePath;
	private Document document;
	private PdfPTable table;
	public PdfExportSvcImpl(String path,int colNum) {
		filePath = path.replace("\\\\", "\\").replace("\\", "/");
		int index = filePath.lastIndexOf("/");
		String fileDir = filePath.substring(0,index);
		String form = filePath.substring(filePath.lastIndexOf("."));
		Validate.isTrue(".pdf".equalsIgnoreCase(form),"输入的文件路径后缀必须为.pdf");
		File dirFile = new File(fileDir);
		if(!dirFile.exists()) {
			dirFile.mkdirs();
		}
		document = new Document();
		try {
			PdfWriter.getInstance(document, new FileOutputStream(new File(path)));
		} catch (Exception e) {
			e.printStackTrace();
		} 
		document.open();
		//创建pdf-->table
		table = new PdfPTable(colNum);
	}
	/**
	 * @throws Exception
	 * @see com.asiainfo.bi.report.framework.util.export.ExportSvc#writeData(java.util.List,
	 *      java.lang.Integer)
	 */
	public void writeData(List<Object[]> dataSet, Integer index) {
		try {
			for (Object[] t : dataSet) {
				writeData(t, null);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * @see com.asiainfo.bi.report.framework.util.export.ExportSvc#writeData(java.lang.Object[],
	 *      java.lang.Integer)
	 */
	public void writeData(Object[] t, Integer index) {
		try {
			for (int i = 0; i < t.length; i++) {
				BaseFont chinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				Font font = new Font(chinese);
				table.addCell(new Paragraph(String.valueOf(t[i]), font));
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * @see com.asiainfo.bi.report.framework.util.export.ExportSvc#writeTblHead(java.util.List[],
	 *      java.lang.Integer)
	 */
	public void writeTblHead(List<Map<String,Object>>[] heads, Integer index) {
		document.newPage();
		try {
			for (List<Map<String,Object>> cells : heads) {
				for (Map<String,Object> cell : cells) {
					PdfPCell c = new PdfPCell();
					c.setColspan((Integer) cell.get("colspan"));
					c.setRowspan((Integer) cell.get("rowspan"));
					BaseFont chinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
					Font font = new Font(chinese);
					c.addElement(new Paragraph((String)cell.get("alias"), font));
					table.addCell(c);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * @see com.asiainfo.bi.report.framework.util.export.ExportSvc#writeFile(java.io.File)
	 */
	public void writeFile(boolean needZip,String waterMarkName) {
		try {
			document.add(table);
		} catch (DocumentException e) {
			e.printStackTrace();
		}finally{
			document.close();
		}
		//压缩
		if(needZip){
			String zipPath = filePath.substring(0,filePath.lastIndexOf(".")) +".zip";
			ZipUtil.compress(filePath, zipPath);
		}
		//添加水印
		if(StringUtils.isNotEmpty(waterMarkName)) {
			waterMark(null,waterMarkName);
		}
	}
	
	/**
	 * @param imageFile 如果有需要时可以加图片,暂时代码中的图片是隐掉了
	 * @param waterMarkName  水印的文字
	 */
	public void waterMark(String imageFile, String waterMarkName) {  
	        try {  
	            PdfReader reader = new PdfReader(filePath);  
	            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(  
	                    filePath+".tmp"));
	            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
	            int total = reader.getNumberOfPages() + 1;  
	            Rectangle pageRect = null;
	            // Image image = Image.getInstance(imageFile);  
	            // 图片位置  
	            // image.setAbsolutePosition(400, 480);  
	            PdfContentByte under;  
	            int j = waterMarkName.length();  
	            char c = 0;
	            int rise = 0;
	            for (int i = 1; i < total; i++) {
	                pageRect = stamper.getReader().
	                        getPageSizeWithRotation(i);
	                     // 计算水印X,Y坐标
	                float x = pageRect.getWidth() / 2;
	                float y = pageRect.getHeight() / 2;
	                rise = 400;  
	                under = stamper.getUnderContent(i);  
	                under.beginText();  
	                under.setFontAndSize(base, 30);  
	                under.setLineWidth(1f);
	                under.setColorFill(BaseColor.LIGHT_GRAY);
	                under.showTextAligned(Element.ALIGN_CENTER ,
	                        waterMarkName, x, y, 45); 
//	                if (j >= 15) {  
//	                    under.setTextMatrix(200, 120);  
//	                    for (int k = 0; k < j; k++) {  
//	                        under.setTextRise(rise);  
//	                        c = waterMarkName.charAt(k);  
//	                        under.showText(c + "");
//	                        rise -= 12;
//	                    }  
//	                } else {  
//	                    under.setTextMatrix(240, 100);  
//	                    for (int k = 0; k < j; k++) {  
//	                        under.setTextRise(rise);  
//	                        c = waterMarkName.charAt(k);  
//	                        under.showText(c + "");  
//	                        rise -= 18;  
//	                    }  
//	                }  
	                // 添加水印文字  
	                under.endText();  
	                // 添加水印图片  
	                //under.addImage(image);
//	                under.ellipse(250, 450, 350, 550);//画园
	                under.stroke();  
	            }
	            stamper.close();
	            reader.close();
	            new File(filePath).delete();
	            File tmpFile = new File(filePath + ".tmp");
	            tmpFile.renameTo(new File(filePath));
	            tmpFile.delete();
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    }  
}
